package com.zcdyy.rentalofhouse.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zcdyy.rentalofhouse.application.MyApplication;
import com.zcdyy.rentalofhouse.bean.Account;
import com.zcdyy.rentalofhouse.bean.AllRental;
import com.zcdyy.rentalofhouse.bean.Comment;
import com.zcdyy.rentalofhouse.bean.OrderInfo;
import com.zcdyy.rentalofhouse.bean.SaleHouse;
import com.zcdyy.rentalofhouse.bean.ShopRent;
import com.zcdyy.rentalofhouse.bean.SingleRent;
import com.zcdyy.rentalofhouse.constant.Constants;
import com.zcdyy.rentalofhouse.ui.activity.LoginActivity;
import com.zcdyy.rentalofhouse.ui.activity.MainActivity;
import com.zcdyy.rentalofhouse.ui.activity.MyRentalActivity;
import com.zcdyy.rentalofhouse.ui.activity.RegisterActivity;
import com.zcdyy.rentalofhouse.ui.activity.SaleActivity;
import com.zcdyy.rentalofhouse.ui.activity.ShopsActivity;
import com.zcdyy.rentalofhouse.ui.activity.SingleRentActivity;
import com.zcdyy.rentalofhouse.ui.activity.WholeRentDetailsActivity;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by chuan on 2017/3/10.
 */

public class BmobUtils {
    public static boolean loginSuccess = false;
    public static boolean query = false;
    public static int queryCount = 0;
    private boolean registerSuccess = true;
    private Context context;
    public BmobUtils(Context context){
        this.context = context;
    }

    public void saveCommentInfo(Comment comment, final int resultCode, final int failedCode, final Handler handler ){
        comment.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("saveCommentInfo", "ok");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    handler.sendEmptyMessage(failedCode);
                    Log.e("saveCommentInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 获取评论
     * @param resultCode
     * @param failedCode
     * @param handler
     */
    public void getCommentInfo(String id, final int resultCode, final int failedCode, final Handler handler){
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("rentalId",id);
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e==null){
                    Log.e("getCommentInfo","ok");
                    Collections.reverse(list);
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    message.what = resultCode;
                    bundle.putSerializable("list", (Serializable) list);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }else {
                    handler.sendEmptyMessage(failedCode);
                    Log.e("getCommentInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 增加用户
     * @param account
     */
    public void addUserInfo(final Account account) {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    ((RegisterActivity) context).account.setId(s);
                    updateAccountInfo(((RegisterActivity) context).account);
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("Bmob-updateInfoFailed", e.getMessage());
                }
            }
        });
    }

    public void getBackYourAccount(final String phone, final String userPassword){
        final BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e == null){
                    Log.e("getBackYourAccount", "ok");
                    for (Account a :
                            list) {
                        if (a.getAccount().equals(phone)){
                            Account account = new Account();
                            account.setId(a.getId());
                            account.setAccount(a.getAccount());
                            account.setNikeName(a.getNikeName());
                            account.setHead(a.getHead());
                            account.setRealName(a.getRealName());
                            account.setPassword(userPassword);
                            findPassword(account);
                            break;
                        }
                    }
                }else {
                    Log.e("getBackYourAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 注册新用户验证
     * @param userPhone 账号
     */
    public void registerChecked(final String userPhone) {
        BmobQuery<Account> query = new BmobQuery<>();
        query.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                for (Account a :
                        list) {
                    if (a.getAccount().equals(userPhone)) {
                        registerSuccess = false;
                        break;
                    }
                }
                if (!registerSuccess) {
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_FAILED);
                } else {
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_SUCCESS);
                }
            }
        });
    }
    /**
     * 登录查询是否账号密码输入错误
     */
    public void queryAccount(final Account account) {
        BmobQuery<Account> bmobQuery = new BmobQuery<>();
        bmobQuery.findObjects(new FindListener<Account>() {
            @Override
            public void done(List<Account> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (Account a :
                            list) {
                        if (a.getAccount().equals(account.getAccount()) && a.getPassword().equals(account.getPassword())) {
                            loginSuccess = true;
                            MyApplication.getInstance().saveUserInfo(a);
//                            ((LoginActivity) context).account.setId(a.getObjectId());
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", "Failed");
                }
                ((LoginActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
            }
        });
    }

    /**
     * 更新用户密码
     *
     * @param account
     */
    public void findPassword(Account account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }
    /**
     * 更新用户信息
     *
     * @param account
     */
    public void updateAccountInfo(Account account) {
        Log.e("更新用户信息",account.getId());
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传图片文件
     *
     * @param bmobFile
     */
    public void upLoadFile(final BmobFile bmobFile, final int code, final Handler handler) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Account account = MyApplication.getInstance().readLoginUser();
                    account.setHead(bmobFile);
                    MyApplication.getInstance().saveUserInfo(account);
                    updateAccountInfo(account);

                    handler.sendEmptyMessage(code);
                    Log.e("upLoadFile", "ok--" + bmobFile.getFileUrl());
                } else {
                    e.printStackTrace();
                    Log.e("upLoadFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传商铺的图片
     * @param bmobFile
     */
    public void upLoadShopFile(final BmobFile bmobFile){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ((ShopsActivity) context).orderInfo.setPic(bmobFile);
                    ((ShopsActivity) context).shopRent.setPic(bmobFile);
                    Log.e("upLoadShopFile", "ok--" + bmobFile.getFileUrl());
                    ((ShopsActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("upLoadShopFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传商铺信息
     * @param shopRent
     * @param orderInfo
     */
    public void uploadShopRent(final ShopRent shopRent, final OrderInfo orderInfo){
        shopRent.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("uploadShopRent", "ok");
                    orderInfo.setTypeID(shopRent.getObjectId());
                    upShopOrderInfo(orderInfo);
                } else {
                    e.printStackTrace();
                    Log.e("uploadShopRent", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传商铺的OrderInfo
     * @param orderInfo
     */
    public void upShopOrderInfo(OrderInfo orderInfo){
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("uploadShopRent", "ok");
                    ((ShopsActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("uploadShopRent", e.getMessage());
                }
            }
        });
    }
    /**
     * 上传发布界面图片文件----整租图片
     *
     * @param bmobFile
     */
    public void upPublishFile(final BmobFile bmobFile) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ((WholeRentDetailsActivity) context).orderInfo.setPic(bmobFile);//这里设置图片
                    ((WholeRentDetailsActivity) context).allRental.setPic(bmobFile);
                    Log.e("upPublishFile", "ok--" + bmobFile.getFileUrl());
                    ((WholeRentDetailsActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("upPublishFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 二手房上传发布界面图片文件
     */
    public void upHouseFile(final BmobFile bmobFile) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ((SaleActivity) context).orderInfo.setPic(bmobFile);
                    ((SaleActivity) context).saleHouse.setPic(bmobFile);
                    ((SaleActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);//上传成功，通知Handler可以发布信息了
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 单间上传发布界面图片文件
     */
    public void upSingleFile(final BmobFile bmobFile) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ((SingleRentActivity) context).orderInfo.setPic(bmobFile);
                    ((SingleRentActivity) context).singleRent.setPic(bmobFile);
                    ((SingleRentActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);//上传成功，通知Handler可以发布信息了
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 上传整租的信息
     */
    public void upLoadAllRental(final AllRental allRental, final OrderInfo orderInfo) {
        allRental.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("upLoadAllRental", "ok--");
                    orderInfo.setTypeID(allRental.getObjectId());//将整租的表与typeId联系起来
                    upLoadOrderInfo(orderInfo);//上传Order信息
                } else {
                    //e.printStackTrace();
                    Log.e("upLoadAllRental", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传二手房的信息
     */
    public void upHouseRental(final SaleHouse saleHouse, final OrderInfo orderInfo) {
        saleHouse.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    orderInfo.setTypeID(saleHouse.getObjectId());
                    upLoadHouseOrderInfo(orderInfo);
                } else {

                }
            }
        });
    }

    /**
     * 上传单间的信息
     */
    public void upSingleRental(final SingleRent singleRent, final OrderInfo orderInfo) {
        singleRent.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    orderInfo.setTypeID(singleRent.getObjectId());
                    upSingleOrderInfo(orderInfo);
                } else {

                }
            }
        });
    }


    /**
     * 上传OrderInfo首页的展示---整租
     * @param orderInfo
     */
    public void upLoadOrderInfo(OrderInfo orderInfo){
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("upLoadOrderInfo", "ok--");
                    ((WholeRentDetailsActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                } else {
                    //e.printStackTrace();
                    Log.e("upLoadOrderInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传二手房的OrderInfo首页的展示
     */

    public void upLoadHouseOrderInfo(OrderInfo orderInfo) {
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    ((SaleActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                } else {
                    Log.e("upLoadOrderInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传单间的OrderInfo首页的展示
     */

    public void upSingleOrderInfo(OrderInfo orderInfo) {
        orderInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    ((SingleRentActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                } else {

                }
            }
        });
    }
    /**
     * 查询发布的信息
     */
    public void queryOrderInfo(){
        BmobQuery<OrderInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<OrderInfo>() {
            @Override
            public void done(List<OrderInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("queryOrderInfo", "ok--");
                    Collections.reverse(list);
                    RentalUtils.list_order.clear();
                    RentalUtils.list_order.addAll(list);
                    Intent intent = new Intent("download");
                    //intent.putExtra("load",1);
                    context.sendBroadcast(intent);
                 } else {
                    //e.printStackTrace();
                    Log.e("queryOrderInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询整租的全部信息
     */
    public void queryAllRental() {
        BmobQuery<AllRental> query = new BmobQuery<>();
        query.findObjects(new FindListener<AllRental>() {
            @Override
            public void done(List<AllRental> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAllRental", "ok--");
                    Collections.reverse(list);
                    RentalUtils.list_allRental.clear();
                    RentalUtils.list_allRental.addAll(list);
                    Intent intent = new Intent("download");
                    //intent.putExtra("load",1);
                    context.sendBroadcast(intent);
                } else {

                    Log.e("queryAllRental", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询二手房
     */
    public void querySaleHouse() {
        BmobQuery<SaleHouse> query = new BmobQuery<>();
        query.findObjects(new FindListener<SaleHouse>() {
            @Override
            public void done(List<SaleHouse> list, BmobException e) {
                if (e == null) {
                    Log.e("querySaleHouse", "ok--");
                    Collections.reverse(list);
                    RentalUtils.list_saleHouse.clear();
                    RentalUtils.list_saleHouse.addAll(list);
                    Intent intent = new Intent("download");
                    //intent.putExtra("load",1);
                    context.sendBroadcast(intent);
                } else {

                    Log.e("querySaleHouse", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询单间出租
     */
    public void querySingleRent() {
        BmobQuery<SingleRent> query = new BmobQuery<>();
        query.findObjects(new FindListener<SingleRent>() {
            @Override
            public void done(List<SingleRent> list, BmobException e) {
                if (e == null) {
                    Log.e("querySingleRent", "ok--");
                    Collections.reverse(list);
                    RentalUtils.list_singleRent.clear();
                    RentalUtils.list_singleRent.addAll(list);
                    Intent intent = new Intent("download");
                    //intent.putExtra("load",1);
                    context.sendBroadcast(intent);
                } else {

                    Log.e("querySingleRent", e.getMessage());
                }
            }
        });
    }

    /**
     * 查询商铺
     */
    public void queryShopRent() {
        BmobQuery<ShopRent> query = new BmobQuery<>();
        query.findObjects(new FindListener<ShopRent>() {
            @Override
            public void done(List<ShopRent> list, BmobException e) {
                if (e == null) {
                    Log.e("queryOrderInfo", "ok--");
                    Collections.reverse(list);
                    RentalUtils.list_shopRent.clear();
                    RentalUtils.list_shopRent.addAll(list);
                    Intent intent = new Intent("download");
                    //intent.putExtra("load",1);
                    context.sendBroadcast(intent);
                } else {

                    Log.e("queryOrderInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 删除
     * @param orderInfo
     */
    public void deleteRental(OrderInfo orderInfo){
        orderInfo.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("deleteRental", "ok");
                    BmobUtils.query = false;
                    BmobUtils.queryCount = 0;
                    ((MyRentalActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                    ToastUtils.shortToast(context,"删除成功");

                } else {
                    Log.e("deleteRental", e.getMessage());
                }
            }
        });
    }
}
